package com.mutual.assistance.media.api;

import com.mutual.assistance.exception.BizException;
import com.mutual.assistance.media.model.dto.MediaFilesDTO;
import com.mutual.assistance.media.model.dto.UploadFileResultDto;
import com.mutual.assistance.media.model.vo.DownloadFileParamsVO;
import com.mutual.assistance.media.model.vo.QueryMediaParamsVO;
import com.mutual.assistance.media.model.vo.UploadFileParamsVO;
import com.mutual.assistance.media.service.MediaFileService;
import com.mutual.assistance.response.PageParams;
import com.mutual.assistance.response.PageResult;
import com.mutual.assistance.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Objects;

import static com.mutual.assistance.exception.code.ExceptionCode.INTERNAL_SERVER_ERROR;

/**
 * @author chenyuxin
 * @version 1.0
 * @description 文件上次与下载接口
 * @date 2023/4/15 14:15
 */
@RestController
@Api(tags = "文件上次与下载接口")
@Slf4j
public class MediaFilesController {

    @Resource
    private MediaFileService mediaFileService;

    @Value("${minio.bucket.files}")
    private String bucketFiles;

    @ApiOperation("上传文件")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "上传的文件", required = true),
            @ApiImplicitParam(name = "folder", value = "存储文件的路径", required = false),
            @ApiImplicitParam(name = "objectName", value = "自定义文件的名称", required = false)
    })
    public R<UploadFileResultDto> upload(
            @RequestPart("file") MultipartFile file,
            @RequestParam(value = "folder", required = false) String folder,
            @RequestParam(value = "objectName", required = false) String objectName
    ) throws IOException {
        UploadFileParamsVO uploadFileParamsVO = new UploadFileParamsVO();
        uploadFileParamsVO.setContentType(file.getContentType());
        uploadFileParamsVO.setFileSize(file.getSize());

        if (Objects.requireNonNull(file.getContentType()).contains("image")) {
            uploadFileParamsVO.setFileType("001001");
        } else {
            uploadFileParamsVO.setFileType("001003");
        }

        uploadFileParamsVO.setFilename(file.getOriginalFilename());
        UploadFileResultDto uploadFileResultDto = mediaFileService.uploadFile(uploadFileParamsVO, file.getBytes(), folder, objectName);
        return R.success(uploadFileResultDto, "上传成功");
    }

    @ApiOperation("下载安卓apk")
    @GetMapping("/open/apk")
    public void downloadAndroidApk(HttpServletResponse response) {
        DownloadFileParamsVO downloadFileParamsVO = new DownloadFileParamsVO();
        try {
            File file = File.createTempFile("temp", null);
            downloadFileParamsVO.setFile(file);
            downloadFileParamsVO.setBucket(bucketFiles);
            downloadFileParamsVO.setObjectName("android/app.apk");
            File downloadFileFromMinIO = mediaFileService.downloadFileFromMinIO(downloadFileParamsVO);
            InputStream inputStream = Files.newInputStream(downloadFileFromMinIO.toPath());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            String fileName = "app.apk";
            fileName = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
            response.addHeader("Content-Disposition", "filename=" + fileName);
            OutputStream outputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer,0, len);
            }
            outputStream.close();
        } catch (IOException e) {
            throw new BizException(INTERNAL_SERVER_ERROR.getCode(), "下载失败");
        }
    }

    @ApiOperation("媒资列表查询接口")
    @GetMapping("/files")
    @PreAuthorize("hasAuthority('mediamanager_file_view')")
    public R<PageResult<MediaFilesDTO>> list(PageParams pageParams, QueryMediaParamsVO queryMediaParamsVO) {
        PageResult<MediaFilesDTO> pageResult = mediaFileService.queryMediaFiles(pageParams, queryMediaParamsVO);
        return R.success(pageResult, "获取成功");
    }

}
